﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Db4objects.Db4o;

namespace CDDocumentExtractor
{
    public partial class frmDocumentExtractor : Form
    {
        Db4objects.Db4o.IObjectContainer db = DataAccess.GetDataContainer();
        string exp = "<manuid\\b[^>]*>(.*?)</manuid>";
        System.Text.RegularExpressions.Regex rx;
        List<DocumentsToDownload> documents;
        int itemCount = 0;

        public frmDocumentExtractor()
        {
            InitializeComponent();
        }

        private void frmDocumentExtractor_Load(object sender, EventArgs e)
        {
            this.FormClosing += new FormClosingEventHandler(frmDocumentExtractor_FormClosing);
            rx = new System.Text.RegularExpressions.Regex(exp, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            documents = db.Query<DocumentsToDownload>(doc => doc.Downloaded.Equals(false)).ToList();
            //lblDocumentsToProcess.Text = string.Format("Total {0} Documents to process.", documents.Count.ToString());
            lblDocumentsToProcess.Text = string.Format("Total {0} Documents to process.", documents.Count.ToString());

            progressBar1.Minimum = 1;
            progressBar1.Maximum = documents.Count;
        }

        void frmDocumentExtractor_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                db.Close();
            }
            catch { }
            }

        private string WriteDocumentToFile(string documentData)
        {
            //Get Manu id from the document
            var match = rx.Match(documentData);
            string val = "";
            if (match != null && match.Success)
            {
                val = System.Text.RegularExpressions.Regex.Replace(match.Value, "<.*?>", string.Empty);
                string val1 = val.Replace('/', '_') + ".txt";
                var filePath = Path.Combine(WebUtility.Read("sourceDocuments"), val1);

                File.WriteAllText(filePath, documentData);
            }
            return val;
        }

        private void cmdProcess_Click(object sender, EventArgs e)
        {
            cmdProcess.Enabled = false;

            rtfDocument.Text = "";
            rtfFiles.Text = "";

            for (int i = 0; i < documents.Count; i++)
            {
                itemCount++;
                progressBar1.Value = i + 1;
                Application.DoEvents();
                try
                {
                    WebUtility wu = new WebUtility();
                    string doc = wu.RequestDocument(documents[i].DocumentDownloadPath);

                    if (doc.ToUpper().Contains("THIS ACCESS DENIED ERROR PAGE"))
                    {
                        MessageBox.Show("Server not ready. Please try after some time.");
                        this.Close();
                        return;
                    }

                    rtfDocument.Text = doc;

                    //Write Document and Update Manu ID
                    documents[i].ManuID = WriteDocumentToFile(doc);
                    //Failed Documents
                    if (documents[i].ManuID.Trim().Length <= 0)
                        throw new Exception("Document Failed");
                    
                    documents[i].Downloaded = true;
                    db.Store(documents[i]);

                    //Add Document to Processed List
                    rtfFiles.AppendText(documents[i].ManuID + Environment.NewLine);
                }
                catch
                {
                    File.WriteAllText(WebUtility.Read("errorFile"), documents[i].DocumentDownloadPath);
                }
                Application.DoEvents();

                if (itemCount == 1000)
                {
                    db.Commit();
                    itemCount = 0;
                }
                System.Threading.Thread.Sleep(new TimeSpan(0, 0, 1));
            }
            //Final Commit
            db.Commit();

            MessageBox.Show("Document Extraction Complete");
            this.Close();
        }
    }
}
/*

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Db4objects.Db4o;

namespace CDDocumentExtractor
{
    public partial class frmDocumentExtractor : Form
    {
        //Db4objects.Db4o.IObjectContainer db = DataAccess.GetDataContainer();
        DataView dv;
        string exp = "<manuid\\b[^>]*>(.*?)</manuid>";
        System.Text.RegularExpressions.Regex rx;

        public frmDocumentExtractor()
        {
            InitializeComponent();
        }

        private void frmDocumentExtractor_Load(object sender, EventArgs e)
        {
            this.FormClosing += new FormClosingEventHandler(frmDocumentExtractor_FormClosing);
            rx = new System.Text.RegularExpressions.Regex(exp, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            //var documents = db.Query<DocumentsToDownload>(doc => doc.Downloaded.Equals(false)).ToList();
            //dgDocuments.DataSource = documents;
            
            //lblDocumentsToProcess.Text = string.Format("Total {0} Documents to process.", documents.Count.ToString());

            DataSet ds = new DataSet();
            if (File.Exists(Path.Combine(Application.StartupPath, "DocumentList.xml")))
            {
                ds.ReadXml(Path.Combine(Application.StartupPath, "DocumentList.xml"));
                dv = new DataView(ds.Tables[0], "", "", DataViewRowState.CurrentRows);
                dgDocuments.DataSource = dv;
                lblDocumentsToProcess.Text = string.Format("Total {0} Documents to process.", dv.Count.ToString());

                progressBar1.Minimum = 1;
                progressBar1.Maximum = dv.Count;

            }

            dgDocuments.AutoResizeColumns();
        }

        void frmDocumentExtractor_FormClosing(object sender, FormClosingEventArgs e)
        {
            //try
            //{
            //    db.Close();
            //}
            //catch { }
            }

        private void WriteDocumentToFile(string documentData)
        {
            //Get Manu id from the document
            var match = rx.Match(documentData);
            if (match != null && match.Success)
            {
                string val = System.Text.RegularExpressions.Regex.Replace(match.Value, "<.*?>", string.Empty);
                val = val.Replace('/', '_') + ".txt";
                var filePath = Path.Combine(@"c:\InfoOneSourceDocuments", val);

                File.WriteAllText(filePath, documentData);
            }
        }
        private void cmdProcess_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                progressBar1.Value = i + 1;
                Application.DoEvents();
                try
                {
                    WebUtility wu = new WebUtility();
                    string doc = wu.RequestDocument(dv[i]["FullDownloadPath"].ToString());

                    WriteDocumentToFile(doc);
                }
                catch
                {
                    File.WriteAllText(@"c:\InfoOneSourceDocuments\ErrorFile.txt", dv[i]["FullDownloadPath"].ToString());
                }
                Application.DoEvents();
                System.Threading.Thread.Sleep(new TimeSpan(0, 0, 1));
            }
        }
    }
}

*/